package cn.xuqiudong.console.module.timer.schedule.ddns.util;

import cn.xuqiudong.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Map;

/**
 * 描述: 获得当前所在主机的ip
 * @author Vic.xu
 * @since 2022-07-28 10:00
 */
public class IpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(IpUtils.class);

    /**
     * ip key
     */
    private static final String IP_KEY = "ip";


    /**
     * 获得当前所在主机的ip
     * @return ip
     * @throws IOException
     */
    public static String getIp() throws IOException {
        String url = "https://jsonip.com/";
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        HttpResponse response = client.execute(get);
        int code = response.getStatusLine().getStatusCode();
        // 如果请求成功
        if (code == HttpStatus.OK.value()) {
            String json = EntityUtils.toString(response.getEntity());
            LOGGER.info("getIp json result : {}", json);
            Map<String, Object> map = JsonUtil.jsonToObject(json, new TypeReference<Map<String, Object>>() {
            });
            if (map != null && map.containsKey(IP_KEY)) {
                return (String) map.get(IP_KEY);
            }
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(getIp());
    }
}
